<template>
  <div class="queue-monitor">
    <!-- 队列概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>活跃队列数</span>
              <el-tag type="success">{{ queueStats.activeQueues }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="queueStats.activeQueuesTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(queueStats.activeQueuesTrend) }}%
                <el-icon>
                  <component :is="queueStats.activeQueuesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>积压消息数</span>
              <el-tag type="warning">{{ queueStats.backlogCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="queueStats.backlogTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(queueStats.backlogTrend) }}%
                <el-icon>
                  <component :is="queueStats.backlogTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>消费延迟(ms)</span>
              <el-tag type="danger">{{ queueStats.consumptionDelay }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="queueStats.delayTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(queueStats.delayTrend) }}%
                <el-icon>
                  <component :is="queueStats.delayTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>消费者数量</span>
              <el-tag type="info">{{ queueStats.consumerCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="queueStats.consumerTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(queueStats.consumerTrend) }}%
                <el-icon>
                  <component :is="queueStats.consumerTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 队列性能图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>消息吞吐量趋势</span>
              <el-radio-group v-model="throughputTimeRange" size="small">
                <el-radio-button label="hour">1小时</el-radio-button>
                <el-radio-button label="day">24小时</el-radio-button>
                <el-radio-button label="week">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="throughputChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>消费延迟分布</span>
              <el-radio-group v-model="delayTimeRange" size="small">
                <el-radio-button label="hour">1小时</el-radio-button>
                <el-radio-button label="day">24小时</el-radio-button>
                <el-radio-button label="week">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="delayChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 队列列表 -->
    <el-card shadow="hover" class="queue-list-card">
      <template #header>
        <div class="card-header">
          <span>队列列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索队列名称"
              style="width: 200px"
              clearable
              @clear="handleSearch"
            />
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table :data="queueList" border v-loading="loading">
        <el-table-column prop="name" label="队列名称" min-width="150" />
        <el-table-column prop="type" label="队列类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getQueueTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="messageCount" label="消息数量" width="120" />
        <el-table-column prop="consumerCount" label="消费者数量" width="120" />
        <el-table-column prop="avgDelay" label="平均延迟(ms)" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '活跃' : '暂停' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
              <el-button type="primary" link @click="handlePauseQueue(row)" v-if="row.status === 'active'">
                暂停
              </el-button>
              <el-button type="primary" link @click="handleResumeQueue(row)" v-else>
                恢复
              </el-button>
              <el-button type="primary" link @click="handlePurgeQueue(row)">清空</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 队列详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="队列详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="队列名称">{{ currentQueue.name }}</el-descriptions-item>
        <el-descriptions-item label="队列类型">{{ getQueueTypeLabel(currentQueue.type) }}</el-descriptions-item>
        <el-descriptions-item label="消息数量">{{ currentQueue.messageCount }}</el-descriptions-item>
        <el-descriptions-item label="消费者数量">{{ currentQueue.consumerCount }}</el-descriptions-item>
        <el-descriptions-item label="平均延迟">{{ currentQueue.avgDelay }}ms</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentQueue.status === 'active' ? 'success' : 'info'">
            {{ currentQueue.status === 'active' ? '活跃' : '暂停' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentQueue.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间">{{ formatDateTime(currentQueue.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentQueue.description }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>消费者列表</el-divider>

      <el-table :data="consumerList" border>
        <el-table-column prop="id" label="消费者ID" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '活跃' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastActiveTime" label="最后活跃时间" width="180">
          <template #default="{ row }">{{ formatDateTime(row.lastActiveTime) }}</template>
        </el-table-column>
        <el-table-column prop="processedCount" label="已处理消息数" width="120" />
        <el-table-column prop="errorCount" label="错误数" width="100" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getQueueStats,
  getQueueList,
  getQueueDetail,
  pauseQueue,
  resumeQueue,
  purgeQueue,
  getQueueThroughputData,
  getQueueDelayData
} from '@/api/message'

// 队列统计数据
const queueStats = reactive({
  activeQueues: 0,
  activeQueuesTrend: 0,
  backlogCount: 0,
  backlogTrend: 0,
  consumptionDelay: 0,
  delayTrend: 0,
  consumerCount: 0,
  consumerTrend: 0
})

// 图表相关
const throughputChartRef = ref(null)
const delayChartRef = ref(null)
let throughputChart = null
let delayChart = null
const throughputTimeRange = ref('hour')
const delayTimeRange = ref('hour')

// 队列列表
const queueList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const searchKeyword = ref('')

// 详情对话框
const detailDialogVisible = ref(false)
const currentQueue = reactive({})
const consumerList = ref([])

// 加载队列统计数据
const loadQueueStats = async () => {
  try {
    const res = await getQueueStats()
    Object.assign(queueStats, res.data)
  } catch (error) {
    ElMessage.error('加载队列统计数据失败')
  }
}

// 初始化吞吐量图表
const initThroughputChart = () => {
  if (!throughputChartRef.value) return
  throughputChart = echarts.init(throughputChartRef.value)
  updateThroughputChart()
}

// 更新吞吐量图表
const updateThroughputChart = async () => {
  if (!throughputChart) return
  try {
    const res = await getQueueThroughputData({ timeRange: throughputTimeRange.value })
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['生产速率', '消费速率']
      },
      xAxis: {
        type: 'category',
        data: res.data.timestamps
      },
      yAxis: {
        type: 'value',
        name: '消息/秒'
      },
      series: [
        {
          name: '生产速率',
          type: 'line',
          data: res.data.productionRates,
          smooth: true
        },
        {
          name: '消费速率',
          type: 'line',
          data: res.data.consumptionRates,
          smooth: true
        }
      ]
    }
    throughputChart.setOption(option)
  } catch (error) {
    ElMessage.error('加载吞吐量数据失败')
  }
}

// 初始化延迟图表
const initDelayChart = () => {
  if (!delayChartRef.value) return
  delayChart = echarts.init(delayChartRef.value)
  updateDelayChart()
}

// 更新延迟图表
const updateDelayChart = async () => {
  if (!delayChart) return
  try {
    const res = await getQueueDelayData({ timeRange: delayTimeRange.value })
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: res.data.timestamps
      },
      yAxis: {
        type: 'value',
        name: '延迟(ms)'
      },
      series: [
        {
          type: 'line',
          data: res.data.delays,
          smooth: true,
          areaStyle: {}
        }
      ]
    }
    delayChart.setOption(option)
  } catch (error) {
    ElMessage.error('加载延迟数据失败')
  }
}

// 加载队列列表
const loadQueueList = async () => {
  try {
    loading.value = true
    const res = await getQueueList({
      page: page.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    queueList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('加载队列列表失败')
  } finally {
    loading.value = false
  }
}

// 查看队列详情
const handleViewDetail = async (row) => {
  try {
    const res = await getQueueDetail(row.id)
    Object.assign(currentQueue, res.data.queue)
    consumerList.value = res.data.consumers
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载队列详情失败')
  }
}

// 暂停队列
const handlePauseQueue = async (row) => {
  try {
    await pauseQueue(row.id)
    ElMessage.success('暂停队列成功')
    loadQueueList()
  } catch (error) {
    ElMessage.error('暂停队列失败')
  }
}

// 恢复队列
const handleResumeQueue = async (row) => {
  try {
    await resumeQueue(row.id)
    ElMessage.success('恢复队列成功')
    loadQueueList()
  } catch (error) {
    ElMessage.error('恢复队列失败')
  }
}

// 清空队列
const handlePurgeQueue = (row) => {
  ElMessageBox.confirm('确定要清空该队列吗？此操作不可恢复！', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await purgeQueue(row.id)
      ElMessage.success('清空队列成功')
      loadQueueList()
    } catch (error) {
      ElMessage.error('清空队列失败')
    }
  })
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadQueueList()
}

// 刷新
const handleRefresh = () => {
  loadQueueStats()
  loadQueueList()
  updateThroughputChart()
  updateDelayChart()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadQueueList()
}

const handleCurrentChange = (val) => {
  page.value = val
  loadQueueList()
}

// 工具方法
const getQueueTypeLabel = (type) => {
  const map = {
    direct: '直连队列',
    fanout: '广播队列',
    topic: '主题队列',
    delay: '延迟队列'
  }
  return map[type] || type
}

const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 监听时间范围变化
watch(throughputTimeRange, () => {
  updateThroughputChart()
})

watch(delayTimeRange, () => {
  updateDelayChart()
})

// 监听窗口大小变化
const handleResize = () => {
  throughputChart?.resize()
  delayChart?.resize()
}

// 初始化
onMounted(() => {
  loadQueueStats()
  loadQueueList()
  initThroughputChart()
  initDelayChart()
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  throughputChart?.dispose()
  delayChart?.dispose()
})
</script>

<style lang="scss" scoped>
.queue-monitor {
  padding: 20px;
  .overview-row {
    margin-bottom: 20px;
    .overview-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .card-content {
        .trend {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;
          .up {
            color: #67c23a;
          }
          .down {
            color: #f56c6c;
          }
        }
      }
    }
  }
  .chart-row {
    margin-bottom: 20px;
    .chart-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .chart-container {
        height: 300px;
      }
    }
  }
  .queue-list-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 